// 分页部分
layui.use( ["jquery", "table", "form", "laypage", "layer", "tree", "api", 'laydate', 'utill'],
  function () {
    var form = layui.form;
    form.render();
    var api = layui.api;
    var table = layui.table;
    var laypage = layui.laypage;
    var $ = layui.jquery;
    var layer = layui.layer;
    var admin = layui.admin;
    var view = layui.view;
    var laydate = layui.laydate;
    var setter = layui.setter;
    var utill = layui.utill;
    var str = sessionStorage.getItem('ipay-merchant')
    var token = JSON.parse(str).token;
    var dqEnglish = layui.sessionData("English").English;
    var labelinp = $(".labelinp");
    var en_ch = dqEnglish ? "data_en" : "data_cn";
    labelinp.each(function (i) {
      $(this).html($(this).attr(en_ch));
    });
    var tableIns = null;
    var tree = layui.tree;
    //渲染 
    admin.req({
      type: "GET",
      url: api.host + api.sbwd.doSelectOption,
      data: {},
      headers: {
        "Content-Type": "application/json",
        'token': layui.sessionData(setter.tableName).token
      },
      async: false,
      dataType: "json",
      success: function (data) {
        if (data.code == "0") {
          var odata = data.data;
          function transferKey(odata) {
            odata.forEach(obj => {
              obj.title = obj.tcCatgName;
              obj.children = obj.childList;
              delete obj["tcCatgName"];
              delete obj["childList"];
              if (obj.children instanceof Array) {
                transferKey(obj.children);
              }
            });
            return odata;
          }
          odataArr = transferKey(odata);
          var inst1 = tree.render({
            elem: "#sheBeiDivbox", //传入元素选择器
            showLine: false, //是否开启连接线
            data: odataArr,
            click: function (node) {
              var obj = {
                pageNum: 0,
                pageSize: 0,
                tcCatgId: node.data.tcCatgId
              };
              odataArr = transferKey(odata);
              selectList(obj);
            }
          });
          let html = `<i class="btn_icon layui-icon layui-icon-triangle-r"></i> `;
          $('.leftNavBar').append(html);
          return odata;
        } else {
          layer.msg(data.message, {
            icon: 5
          });
        }
      }
    });
    var objpage = {
      pageNum: 1,
      pageSize: 20
    };

    var tf = false
    $(".leftNavBar").on("click", function (event) {
      event.stopPropagation();
    });
    utill.showAndHide('#upload','TcEamDocumentController:insertFiaFile');
    utill.showAndHide('#inputButton','TcEamDocumentController:insertFiaFile');
    table.on("toolbar(demo)", function (obj) {
      var checkStatus = table.checkStatus(obj.config.id);
      var data = checkStatus.data;
      switch (obj.event) {
        case "getCheckData":
          if (checkStatus.data.length == 0) {
            parent.layer.msg('至少选择一个哟！', { icon: 2 });
            return;
          }
          var idsarr = []
          for (var i = 0; i < data.length; i++) {
            idsarr.push(data[i].tcDocId)
          }
          var ids = idsarr.join()
          window.open(
            api.host + "/do/downloads.json?ids=" + ids + '&token=' + layui.sessionData(setter.tableName).token
          );
          break;
        case "Edit":
          if (data.length == 1) {
            $(".tc_tree").css("display", "block");
            admin.popup({
              title: '文档编辑',
              area: ['500px', '300px'],
              id: 'LAY-popup-content-tags',
              success: function (layero, index) {
                view(this.id).render('home/alert/edit-alert').done(function () {
                  selectList(obj)
                });
              }
            });
          } else {
            layer.msg("请选择一个编辑");
          }
          break;
        case "ImportDocuments":
          admin.popup({
            title: '文档导入',
            area: ['400px', '480px'],
            id: 'LAY-popup-content-tags',
            success: function (layero, index) {
              sessionStorage.setItem('indexone', index)
              view(this.id).render('home/alert/alert').done(function () {
               
              });
            },
            end: function () { 
              var BJtf=layui.sessionData('BJtf')  
              if(BJtf.truefalse){ 
                selectList(objpage);
              }
            }
          });
          break;
      }
    });
    table.on("tool(demo)", function (obj) {
      var data = obj.data;
      layui.sessionData("demo", {
        key: "tableobj",
        value: data
      });
      var tableobj = layui.sessionData("demo").tableobj;
      switch (obj.event) {
        case "Edit":
          admin.popup({
            title: '编辑',
            area: ['400px', '480px'],
            id: 'LAY-popup-content-tags',
            success: function (layero, index) {
              sessionStorage.setItem('indexone', index)
              view(this.id).render('home/alert/edit-alert').done(function () {

                form.on('submit(LAY-submit)', function (data) {
                  var field = data.field; //获取提交的字段 
                });
              });
            },
            end: function () {
              var BJtf=layui.sessionData('BJtf')  
              if(BJtf.truefalse){ 
                selectList(objpage);
              }
            }
          });
          break;
        case "Down":
          // window.open('www.baidu.com');
          window.open(
            api.host + "/do/downloads.json?ids=" + data.tcDocId + '&token=' + token
          );
          break;
        case "look":
          var htmls = ''
          for (var i = 0; i < data.tcEamFile.length; i++) {
            htmls += '<div style="padding: 20px;"><a target="_blank" href="' + api.imghost + '/' + data.tcEamFile[i].tcFileUrl + '" ><p>' + data.tcEamFile[i].tcFileName + data.tcEamFile[i].tcFileType + '</p></a></div>'
          }
          // // +type //防止重复弹出
          layer.open({
            type: 1
            , offset: 'auto' //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
            , id: 'layerDemo'
            , content: htmls
            , btn: '关闭全部'
            , btnAlign: 'c' //按钮居中
            , shade: 0 //不显示遮罩
            , yes: function () {
              layer.closeAll();
            }
          });
          // window.open(api.imghost + '/' + data.tcEamFile[0].tcFileUrl);
          break;
        case "delete":
          var odata = [data.tcDocId];
          var ajaxOpts = {
            url: api.host + api.sbwd.doDelDocument,
            method: "POST",
            data: JSON.stringify(odata)
          };
          layer.confirm("确定删除吗", function (index) {
            layer.msg("正在操作...", { shade: 0.3, time: 200000000 });
            admin.req({
              headers: {
                "Content-Type": "application/json",
                'token': layui.sessionData(setter.tableName).token
              },
              //   beforeSend: function(xhr) {
              //     xhr.setRequestHeader("authorization",otoken);
              // 	 },
              dataType: "json",
              jsonp: "callback", //传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
              url: api.host + api.sbwd.doDelDocument,
              type: "POST",
              data: JSON.stringify(odata),
              success: function (res) {
                if (res.code == "0") {
                  var success = res.success;
                  var data = res.data;
                  selectList(objpage);
                  obj.del();
                  // //关闭弹框
                  layer.close(index);
                  layer.msg("操作成功", { time: 1000 });
                }
              }
            });
          });
          break;
      }
    });
    var flg = false;
      $('#LAY_app_body').bind("click", function (e) {
        if ($(e.target).closest(".leftNavBar").size() <= 0) {
          $('.leftNavBar').css('width','0px')
                setTimeout(function(){
                  $('.leftNavBar .layui-tree').hide()
                },100)
            flg  = false
        }
    })
    $('.leftNavBar').on('click','.btn_icon',function (e){
      flg  = !flg
        if(flg == true){
            $('.leftNavBar').css('width','180px')
            setTimeout(function(){
              $('.leftNavBar .layui-tree').show()
            },250)
                
        }else if(flg == false){
            setTimeout(function(){
              $('.leftNavBar .layui-tree').hide()
            },100)
                $('.leftNavBar').css('width','0px')
        }
});
    // 列定至弹出层
    $(".layui-table").on("click", ".layui-icon-made", function () {
      layer.open({
        type: 3,
        title: false,
        area: ["368px", "228px"],
        fixed: true,
        shadeClose: true,
        closeBtn: 0,
        skin: "addFri",
        content: [
          "../../../src/views/home/project-one/Customized.html",
          "no"
        ]
      });
    });
    selectList(objpage);
    function selectList(objpage) {
      // 列定制
      utill.columnCustom('#demo', "TcEamDocumentVO", {
        // 自己表格的接口
        url: api.host + api.sbwd.doSelectList,
        where: { 
          tcCatgId:objpage.tcCatgId 
        },
        toolbarh: "#toolbarDemo",
        height: 512,
        toolbar: {
          toolbar: '#tableabtn',
          title: '操作',
          event: 'detail',
          align: 'center'
        }
      });
    }
  }
);